package com.h3bpm.web.organization.controller;

import OThinker.Common.Organization.Models.OrganizationUnit;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.Common.Organization.enums.State;
import OThinker.Common.Organization.enums.UserGender;
import OThinker.Common.Organization.enums.VisibleType;
import OThinker.H3.Controller.ControllerBase;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.engine.client.EngineClient;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.handler.JSONUtils;
import com.h3bpm.handler.Utils.HttpLocalUtils;
import com.h3bpm.handler.domin.EsbReqHead;
import com.h3bpm.web.common.H3Property;
import com.h3bpm.web.common.utils.SqlUtil;
import com.h3bpm.web.config.UrlConfig;
import com.h3bpm.web.organization.service.PushService;
import com.h3bpm.web.protalHanding.OrcaleHelper;
import com.h3bpm.web.protalHanding.ThreadPost;
import data.DataRow;
import data.DataTable;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 因仅供测试使用
 * @Author: VillWang
 * @Date: 2020/6/19 13:33
 */
@RestController
@RequestMapping("/Portal/Push")
//@RequestMapping("/Portal/Pushs")
public class OrgPushController extends ControllerBase {

    @Value("${esb.url}")
    public String ESBURL;
    @Value("${esb.sourceSystem}")
    public String sourceSystem;
    @Value("${esb.targetSystem}")
    public String targetSystem;
    @Value("${esb.userSynServiceName}")
    public String userSynServiceName;
    @Value("${esb.orgSynServiceName}")
    public String orgSynServiceName;

    @Autowired
    PushService pushService;
    private static final Logger logger = LoggerFactory.getLogger(OrgPushController.class);
    public User getAdministrator() throws Exception {
        User user = getEngine().getOrganization().GetUserByCode("Administrator");
        return user;
    }
    /**
     * @Fields serialVersionUID :
     */
    private static final long serialVersionUID = 1951305555362177857L;
    @Override
    public String getFunctionCode() {
        return null;
    }
    private static volatile EngineClient Engine = null;
    private static volatile boolean shouldRefreshEngine = false;
    public static EngineClient getEngine() {
        if (Engine == null || shouldRefreshEngine) {
            try {
                Engine = (EngineClient) AppUtility.getEngine();
            } catch (Exception e) {
                logger.error("get engine fail", e);
                throw new RuntimeException(e);
            }
            shouldRefreshEngine = false;
        }
        return Engine;
    }

    @RequestMapping(value="/OrgUser2")
    public JSONObject organizationSync(@RequestBody String json) throws IOException {
        logger.info("人员数据回写接口-——————json——"+json);
        Map<String, Object> stringObjectMap = JSONUtils.parseMap(json);
        String flag= (String) stringObjectMap.get("flag");
        Map<String,String> data = new HashMap<>();
        data= (Map<String, String>) stringObjectMap.get("data");
        JSONObject result = new JSONObject();
        result.put("code","200");
        logger.info("人员数据回写接口-——————flag——"+flag);
        int i = 1;
        if(StringUtils.isNotBlank(flag)){
            if(data==null||data.equals("")||data.isEmpty()){
                result.put("message","data数据为空");
            }else {
            //新增
            if(flag.equals("1")){
                logger.info("人员数据回写接口-————————新增");
                i =addUser(data);
            //删除
            }else if(flag.equals("2")){
                logger.info("人员数据回写接口-————————删除");
                i=delectUser(data);
            }else {
             //修改
                logger.info("人员数据回写接口-————————修改");
               i= updateUser(data);
            }
            }
        }
        if(i>0){
            result.put("message","success");
        }else {
            result.put("message","flag数据为空");
        }
        return result;
    }
    @RequestMapping(value="/OrgUser")
    public JSONObject organizationSyncUser(@RequestBody String json) throws IOException {
        logger.debug("人员数据回写接口-————————");
        //用户信息推送portal
        //HttpLocalUtils.doPostToESB(ESBURL, json ,new EsbReqHead(
        //        sourceSystem, targetSystem, UUID.randomUUID().toString(), userSynServiceName));
        Map<String, Object> stringObjectMap = JSONUtils.parseMap(json);
        JSONObject result = new JSONObject();
        result.put("code","200");
        int i = 0;
         i=pushService.intoDbo(json,"2");
        if(i>0){
            result.put("message","success");
        }else {
            result.put("message","flag数据为空");
        }
        return result;
    }
    @RequestMapping("/OrgUnit")
    public JSONObject organizationUnit(@RequestBody String json){
        JSONObject result = new JSONObject();
        logger.debug("组织数据回写接口-——————json——"+json);
        //组织机构推送portal
        //HttpLocalUtils.doPostToESB(ESBURL, json ,new EsbReqHead(
        //       sourceSystem, targetSystem, UUID.randomUUID().toString(), orgSynServiceName));
        result.put("code","200");
        int i = 0;
        i=pushService.intoDbo(json,"1");
        if(i>0){
            result.put("message","success");
        }else {
            result.put("message","flag数据为空");
        }
        return result;
    }

    @RequestMapping("/OrgUnit2")
    public JSONObject organizationSyncUnit(@RequestBody String json){
        JSONObject result = new JSONObject();
        logger.info("组织数据回写接口-——————json——"+json);
        Map<String, Object> stringObjectMap = null;
        try {
            stringObjectMap = JSONUtils.parseMap(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String flag= (String) stringObjectMap.get("flag");
        Map<String,String> data = new HashMap<>();
        data= (Map<String, String>) stringObjectMap.get("data");
        result.put("code","200");
        int i = 0;
        if(StringUtils.isNotBlank(flag)){
            if(data==null||data.equals("")||data.isEmpty()){
                result.put("message","data数据为空");
            }else {
                //新增
                if(flag.equals("1")){
                    logger.info("组织数据回写接口-————————新增");
                    i =addUnit(data);
                    //删除
                }else if(flag.equals("2")){
                    logger.info("组织数据回写接口-————————删除");
                    i=delectUnit(data);
                }else {
                    //修改
                    logger.info("组织数据回写接口-————————修改");
                    i= updateUnit(data);
                }
            }
        }
        if(i>0){
            result.put("message","success");
        }else {
            result.put("message","flag数据为空");
        }
        return result;
    }

    private int delectUnit(Map<String, String> data) {
        try {
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
                String dept_idcode=data.get("dept_idcode");
            String sql2 = "SELECT dept_code FROM dbo_unit WHERE dept_idcode='"+dept_idcode+"'";
            DataTable dataTable = SqlUtil.doQuery(sql2);
            String dept_code=dataTable.getEntityRows().get(0).getString("dept_code");
            String getH3UnSql= " select objectid,extend1 from ot_organizationunit  where extend1 = ";
            DataTable isUnit = SqlUtil.doQuery(getH3UnSql + "'" + dept_code+ "'");
            if (isUnit != null && isUnit.getEntityRows().size() > 0) {
                Unit unit = getEngine().getOrganization().GetUnit(isUnit.getEntityRows().get(0).getString("objectid"));
                unit.setState(State.Inactive);
                getEngine().getOrganization().RemoveUnit(getAdministrator().getObjectID(), unit);
                //getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(), unit);
                //删除dbo_user数据
                String sql="DELETE FROM dbo_unit WHERE dept_idcode = '"+data.get("dept_idcode")+"'";
                int i = SqlUtil.doNoQuery(sql);
                return i;
            }
            getEngine().getOrganization().Reload();
        } catch (Exception e) {
                e.printStackTrace();
            }
        return 1;
    }

    private int updateUnit(Map<String, String> data) {
        try {
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String getH3UnSql= " select objectid,extend1 from ot_organizationunit  where extend1 = ";
            DataTable thisUnit = SqlUtil.doQuery(getH3UnSql + "'" + data.get("dept_code") + "'");
            if (thisUnit != null && thisUnit.getEntityRows().size() > 0) {
                Unit unit = getEngine().getOrganization().GetUnit(thisUnit.getEntityRows().get(0).getString("objectid"));
                unit.setName(data.get("dept_content"));//名称
//                unit.setSortKey(0);//排序值
                if (data.get("dept_deleted").equals("1")) {
                    unit.setState(State.Inactive);
                } else {
                    unit.setState(State.Active);
                }
                //Inactive(0),禁用 Active(1),启用 Unspecified(-1);
                unit.setVisibility(VisibleType.Normal); //Normal(1),普通，同AllOnlyAdmin(2),管理员可见OnlyOrganization(4),仅本组织范围可见All(5);
                unit.setParentIndex(0);
                unit.setDescription(data.get("dept_id"));
                unit.setExtend1(data.get("dept_code"));//组织iD
                unit.setExtend2(data.get("dept_parentcode"));//所属组织 上级
                DataTable parentUnit = SqlUtil.doQuery(getH3UnSql+"'"+data.get("dept_parentcode")+"'");
                if(parentUnit!=null && parentUnit.getEntityRows().size()>0 && !"".equals(data.get("dept_parentcode"))) {
                    unit.setParentID(parentUnit.getEntityRows().get(0).getString("objectid"));
                }
                if( "ROOT".equals(data.get("dept_parentcode"))) {
                    unit.setParentID(getEngine().getOrganization().getRootUnit().getObjectID());
                }
                getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(), unit);
               //修改dbo_unit
                String sql="DELETE FROM dbo_unit WHERE dept_idcode = '"+data.get("dept_idcode")+"'";
                int i = SqlUtil.doNoQuery(sql);

                String sql2="INSERT INTO dbo_unit (dept_id,dept_code,dept_content,dept_grade,dept_parentcode,dept_inchargeleader,\n" +
                        "dept_leader,dept_oaorgcode,dept_idcode,dept_ordercode,dept_parentidcode,dept_deleted,dept_type,\n" +
                        "dept_allcontent,dept_endmark,dept_inchargeleaderid,dept_leaderid,dept_parentid," +
                        "dept_instituteleader,dept_leader_approve,dept_instituteleader_approve,dept_inchargeleader_approve,dept_leaderid_approve,dept_instituteleaderid_approve,dept_inchargeleaderid_approve,dept_processtype,dept_instituteleaderid,status)\n" +
                        "VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
                sql2=String.format(sql2,data.get("dept_id"),data.get("dept_code"),data.get("dept_content"),
                        data.get("dept_grade"),data.get("dept_parentcode"),
                        data.get("dept_inchargeleader"),data.get("dept_leader"),data.get("dept_oaorgcode"),
                        data.get("dept_idcode"),data.get("dept_ordercode")
                        ,data.get("dept_parentidcode"),data.get("dept_deleted"),data.get("dept_type"),data.get("dept_allcontent"),
                        data.get("dept_endmark"),data.get("dept_inchargeleaderid"),data.get("dept_leaderid"),data.get("dept_parentid"),data.get("dept_instituteleader"),
                        data.get("dept_leader_approve"),
                        data.get("dept_instituteleader_approve"),
                        data.get("dept_inchargeleader_approve"),
                        data.get("dept_leaderid_approve"),
                        data.get("dept_instituteleaderid_approve"),
                        data.get("dept_inchargeleaderid_approve"),
                        data.get("dept_processtype"),
                        data.get("dept_instituteleaderid"),"1");
                SqlUtil.doNoQuery(sql2);
            }
            getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
        return 1;
    }

    private int addUnit(Map<String, String> data) {
        try {
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("组织数据回写接口-————————dept_code---"+data.get("dept_code"));
            String getH3UnSql= " select objectid,extend1 from ot_organizationunit  where extend1 = ";
                DataTable isUnit = SqlUtil.doQuery(getH3UnSql + "'" + data.get("dept_code") + "'");
            logger.info("组织数据回写接口-————————h3User---"+isUnit);
                if (!(isUnit.getEntityRows().size() > 0) || isUnit == null) {
                    OrganizationUnit unit = new OrganizationUnit();
                    unit.setName(data.get("dept_content"));//名称
                    unit.setIsRootUnit(false);//是否是根节点
                    unit.setSortKey(0);//排序值
                    if (data.get("dept_deleted").equals("1")) {
                        unit.setState(State.Inactive);
                    } else {
                        unit.setState(State.Active);
                    }
                    //Inactive(0),禁用 Active(1),启用 Unspecified(-1);
                    unit.setVisibility(VisibleType.Normal); //Normal(1),普通，同AllOnlyAdmin(2),管理员可见OnlyOrganization(4),仅本组织范围可见All(5);
                    unit.setParentIndex(0);
                    unit.setDescription(data.get("dept_id"));
                    unit.setExtend1(data.get("dept_code"));//组织iD
                    unit.setExtend2(data.get("dept_parentcode"));//所属组织 上级
                    DataTable parentUnit = SqlUtil.doQuery(getH3UnSql+"'"+data.get("dept_parentcode")+"'");
                    if(parentUnit!=null && parentUnit.getEntityRows().size()>0 && !"".equals(data.get("dept_parentcode"))) {
                        unit.setParentID(parentUnit.getEntityRows().get(0).getString("objectid"));
                    }
                    if( "ROOT".equals(data.get("dept_parentcode"))) {
                        unit.setParentID(getEngine().getOrganization().getRootUnit().getObjectID());
                    }
                    //创建组织
                    getEngine().getOrganization().AddUnit(getAdministrator().getObjectID(), unit);

                    String sql2="INSERT INTO dbo_unit (dept_id,dept_code,dept_content,dept_grade,dept_parentcode,dept_inchargeleader,\n" +
                            "dept_leader,dept_oaorgcode,dept_idcode,dept_ordercode,dept_parentidcode,dept_deleted,dept_type,\n" +
                            "dept_allcontent,dept_endmark,dept_inchargeleaderid,dept_leaderid,dept_parentid,status)\n" +
                            "VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
                    sql2=String.format(sql2,data.get("dept_id"),data.get("dept_code"),data.get("dept_content"),
                            data.get("dept_grade"),data.get("dept_parentcode"),
                            data.get("dept_inchargeleader"),data.get("dept_leader"),data.get("dept_oaorgcode"),
                            data.get("dept_idcode"),data.get("dept_ordercode")
                            ,data.get("dept_parentidcode"),data.get("dept_deleted"),data.get("dept_type"),data.get("dept_allcontent"),
                            data.get("dept_endmark"),data.get("dept_inchargeleaderid"),data.get("dept_leaderid"),data.get("dept_parentid"),"1");
                    SqlUtil.doNoQuery(sql2);
            }
            getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
        }
        return 1;
    }

    //更新
    private int updateUser(Map<String, String> map) {
        try {
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
        User h3User = null;
            Boolean flag=false;
            String emp_idcode=map.get("emp_idcode");
            String emp_id=map.get("emp_id");
            String sqlIdcode = "SELECT emp_number FROM dbo_user WHERE emp_id='"+emp_id+"'";
            DataTable dataTable = SqlUtil.doQuery(sqlIdcode);
            String code=dataTable.getEntityRows().get(0).getString("emp_number");
            h3User = getEngine().getOrganization().GetUserByCode(code);
        SimpleDateFormat fm= new SimpleDateFormat("yyyy-mm-dd");
        logger.info("人员数据回写接口-————————emp_number---"+map.get("emp_number"));
        String getH3UnSql= " select objectid,description from ot_organizationunit  where Description = ";
        if(h3User!=null&&!h3User.equals("")) {
            String deptno = "";
            String dept_id = map.get("dept_id");
            if (dept_id == null || "".equals(dept_id)) {
                deptno = getEngine().getOrganization().getRootUnit().getObjectID();
            } else {
                deptno = dept_id;
            }
            DataTable unitTable = SqlUtil.doQuery(getH3UnSql + "'" + deptno + "'");
            if (unitTable.getEntityRows().size() > 0) {
                h3User.setParentID(unitTable.getEntityRows().get(0).getString("objectid"));
            }
            h3User.setState(State.Active);
            //h3User.setEmployeeNumber(map.get("employeeno").toString()); 编号
            String emp_sex = map.get("emp_sex");
            if (map.get("emp_sex") != null && "0".equals(map.get("emp_sex"))) {
                h3User.setGender(UserGender.Male);
            } else {
                h3User.setGender(UserGender.Female);
            }
            String emp_entrydate = map.get("emp_entrydate");
            if (map.get("emp_entrydate") != null && !"".equals(map.get("emp_entrydate"))) {
                h3User.setEntryDate(fm.parse((map.get("emp_entrydate"))));
            }
            String emp_quitdate = map.get("emp_quitdate");
            if (map.get("emp_quitdate") != null && !"".equals(map.get("emp_quitdate"))) {
                h3User.setDepartureDate(fm.parse(map.get("emp_quitdate")));
            }
            String codeBpm=h3User.getCode();
            String emp_number = map.get("emp_number");
            //code相同的不用处理
            if(emp_number.equals(codeBpm)){
                 // h3User.setCode(map.get("emp_number"));
            }else {
                // 不同的数据需要特殊处理
                flag=true;
            }
            String emp_name = map.get("emp_name");
            h3User.setName(map.get("emp_name"));
            String emp_mobilephone = map.get("emp_mobilephone");
            if (map.get("emp_mobilephone") != null) {
                h3User.setMobile(map.get("emp_mobilephone"));
            }
            //String emp_id = map.get("emp_id");
            h3User.setExtend1(map.get("emp_id"));
            getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(), h3User);
            if(flag){
               //需要强制修改user code
               String user="update ot_user set code='"+emp_number+"' where objectId='"+h3User.getObjectID()+"'";
                SqlUtil.doNoQuery(user);
            }
            //修改dbo_user
            logger.info("人员数据回写接口-————————更新OT_user成功");
            //删除dbo_user数据
            String sql="DELETE FROM dbo_user WHERE emp_idcode = '"+map.get("emp_idcode")+"'";
            int i = SqlUtil.doNoQuery(sql);
            logger.info("人员数据回写接口-————————删除dbo");
            //新增dbo_user数据 String.format
            String sql2="INSERT INTO dbo_user (emp_id,emp_idcode,emp_number,emp_name,dept_id,dept_idcode,emp_idnumber,emp_mobilephone,\n" +
                    "emp_projectleader,emp_projectpayee,emp_judgeprojectleader,emp_judgeprojectpayee,emp_incumbencystate,emp_entrydate,\n" +
                    "emp_quitdate,emp_projectleaderid,emp_projectpayeeid,emp_sex,part_type,idtype_content,competentorg_content,\n" +
                    "incumbency_content,emp_numbereffectiveness,empisvalid_content,emp_datavalid,emp_companyemail,emp_personneltype,\n" +
                    "persontype_content,status) \n" +
                    "VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','','%s','%s','%s','%s','%s','%s',\n" +
                    "'%s','%s','%s','%s','%s','%s','%s','%s')";
            String dept_idcode=map.get("dept_idcode");
            String emp_idnumber=map.get("emp_idnumber");
            String emp_projectleader=map.get("emp_projectleader");
            String emp_projectpayee=map.get("emp_projectpayee");
            String emp_judgeprojectleader=map.get("emp_judgeprojectleader");
            String emp_judgeprojectpayee=map.get("emp_judgeprojectpayee");
            String emp_incumbencystate=map.get("emp_incumbencystate");
            String emp_projectleaderid=map.get("emp_projectleaderid");
            String emp_projectpayeeid=map.get("emp_projectpayeeid");
            String part_type=map.get("part_type")!=null?map.get("part_type"):"";//主职
            String idtype_content=map.get("idtype_content")!=null?map.get("idtype_content"):"";//证件类型
            String competentorg_content=map.get("competentorg_content")!=null?map.get("competentorg_content"):"";//主管单位名称
            String incumbency_content=map.get("incumbency_content")!=null?map.get("incumbency_content"):"";//在职状态
            String emp_numbereffectiveness=map.get("emp_numbereffectiveness")!=null?map.get("emp_numbereffectiveness"):"";//员工编号有效性
            String empisvalid_content=map.get("empisvalid_content")!=null?map.get("empisvalid_content"):"";//员工编号有效性
            String emp_datavalid=map.get("emp_datavalid")!=null?map.get("emp_datavalid"):"";//人事资料有效期
            String emp_companyemail=map.get("emp_companyemail")!=null?map.get("emp_companyemail"):"";//公司邮箱
            String emp_personneltype=map.get("emp_personneltype")!=null?map.get("emp_personneltype"):"";//人员类别ID
            String persontype_content=map.get("persontype_content")!=null?map.get("persontype_content"):"";//人员类别
            sql2=String.format(sql2,emp_id,emp_idcode,emp_number,emp_name,dept_id,
                    dept_idcode,emp_idnumber,emp_mobilephone,emp_projectleader,emp_projectpayee
                    ,emp_judgeprojectleader,emp_judgeprojectpayee,emp_incumbencystate,emp_entrydate,
                    emp_projectleaderid,emp_projectpayeeid,emp_sex,part_type,idtype_content,
                    competentorg_content,incumbency_content,emp_numbereffectiveness,empisvalid_content,
                    emp_datavalid,emp_companyemail,emp_personneltype,persontype_content,"1");
            i= SqlUtil.doNoQuery(sql2);
            /**HashMap<String, Object> bms = new HashMap<>();
            String sqlUnit="select dept_content from dbo_unit where dept_id='"+dept_id+"'";
            DataTable data = SqlUtil.doQuery(sqlUnit);
            logger.info("人员数据回写接口-————————新增dbo");
            String dept_content="";
            List<DataRow> entityRows = data.getEntityRows();
            if(!entityRows.isEmpty()&&entityRows.size()>0) {
                 dept_content = entityRows.get(0).getString("dept_content");
            }
            bms.put("globalId",emp_id);
            bms.put("userName",emp_name);
            bms.put("jobNo",emp_number);
            bms.put("phoneNumber",emp_mobilephone);
            bms.put("personnelDept",dept_content);
            String url =  UrlConfig.BusinessUrl+"/" +
                    "prod-api/api/user/updateUserByMdmUser";
            String json = JSONUtils.toJson(bms);
            Map<String, Object> result = ThreadPost.postRequestResult(url,json,null);
            if(result==null||result.size()==0){
                logger.debug("返回值为空—————————————");
            }else {
                int res= (Integer) result.get("code");
                if(res==200){
                    logger.debug("推送业务系统人员====================success");
                }else {
                    logger.debug("推送业务系统人员====================失败");
                }
            }*/
        }
            getEngine().getOrganization().Reload();
        } catch (Exception e) {
                e.printStackTrace();
        }
            return  1;
    }
    //删除
    private int delectUser(Map<String, String> map) {
        try {
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
            SimpleDateFormat fm= new SimpleDateFormat("yyyy-mm-dd");
        User h3User = null;
        String emp_id=map.get("emp_id");
        String sql2 = "SELECT emp_number FROM dbo_user WHERE emp_id='"+emp_id+"'";
        DataTable dataTable = SqlUtil.doQuery(sql2);
        String code=dataTable.getEntityRows().get(0).getString("emp_number");
        h3User = getEngine().getOrganization().GetUserByCode(code);
        if(h3User!=null) {
            if(code.contains("H04")){
                h3User.setState(State.Inactive);
                getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(), h3User);
            }else {
                String sqlDel="DELETE FROM ot_user WHERE objectID = '"+h3User.getObjectID()+"'";
                SqlUtil.doNoQuery(sqlDel);
            }
            //删除dbo_user数据
            String sql="DELETE FROM dbo_user WHERE emp_idcode = '"+map.get("emp_idcode")+"'";
            int i = SqlUtil.doNoQuery(sql);
            return i;
        }
            getEngine().getOrganization().Reload();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  0;
    }

    /**
     *
     *@describe  新增
     *@params [data]
     *@return int
     *@author VillWang
     *@date 2020/6/19
     *@other
     *
     */
    public int addUser(Map<String,String> map){
        try {
            getEngine().getOrganization().Reload();
            String getH3UnSql= " select objectid,description from ot_organizationunit  where Description = ";
        SimpleDateFormat fm= new SimpleDateFormat("yyyy-mm-dd");
        //如果人员不存在则新增此人员
         String emp_idcode=map.get("emp_idcode");
            String emp_id=map.get("emp_id");
        User h3User=new User();
            String sql2 = "SELECT emp_number FROM dbo_user WHERE emp_id='"+emp_id+"'";
            DataTable dataTable = SqlUtil.doQuery(sql2);
            List<DataRow> entityRows = dataTable.getEntityRows();
            if(!entityRows.isEmpty()&&entityRows.size()>0){
                logger.info("人员数据回写接口-————————已存在");
            }else {
        String deptno ="";
        String dept_id =  map.get("dept_id");
        if(dept_id==null || "".equals(dept_id)){
            deptno=getEngine().getOrganization().getRootUnit().getObjectID();
        }else{
            deptno = dept_id;
        }
        DataTable unitTable = SqlUtil.doQuery(getH3UnSql+"'"+deptno+"'");
        if( unitTable.getEntityRows().size()>0){
            h3User.setParentID(unitTable.getEntityRows().get(0).getString("objectid"));
        }
        h3User.setState(State.Active);
        //h3User.setEmployeeNumber(map.get("employeeno").toString()); 编号
          String emp_sex= map.get("emp_sex");
        if(map.get("emp_sex")!=null && "0".equals(map.get("emp_sex"))) {
            h3User.setGender(UserGender.Male);
        }else{
            h3User.setGender(UserGender.Female);
        }
            String emp_entrydate= map.get("emp_entrydate");
        if(map.get("emp_entrydate")!=null && !"".equals(map.get("emp_entrydate"))){
            h3User.setEntryDate(fm.parse((map.get("emp_entrydate"))));
        }
            String emp_quitdate= map.get("emp_quitdate");
        if(map.get("emp_quitdate")!=null && !"".equals(map.get("emp_quitdate"))) {
            h3User.setDepartureDate(fm.parse(map.get("emp_quitdate")));
        }
            String emp_number= map.get("emp_number");
        h3User.setCode(map.get("emp_number"));
            String emp_name= map.get("emp_name");
        h3User.setName(map.get("emp_name"));
            String emp_mobilephone= map.get("emp_mobilephone");
        if(map.get("emp_mobilephone")!=null) {
            h3User.setMobile(map.get("emp_mobilephone"));
        }
        h3User.setExtend1(map.get("emp_id"));
        getEngine().getOrganization().AddUnit(getAdministrator().getObjectID(), h3User);

        //新增dbo_user数据 String.format
            String sql="INSERT INTO dbo_user (emp_id,emp_idcode,emp_number,emp_name,dept_id,dept_idcode,emp_idnumber,emp_mobilephone,\n" +
                    "emp_projectleader,emp_projectpayee,emp_judgeprojectleader,emp_judgeprojectpayee,emp_incumbencystate,emp_entrydate,\n" +
                    "emp_quitdate,emp_projectleaderid,emp_projectpayeeid,emp_sex,part_type,idtype_content,competentorg_content,\n" +
                    "incumbency_content,emp_numbereffectiveness,empisvalid_content,emp_datavalid,emp_companyemail,emp_personneltype,\n" +
                    "persontype_content,status) \n" +
                    "VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','','%s','%s','%s','%s','%s','%s',\n" +
                    "'%s','%s','%s','%s','%s','%s','%s','%s')";
            //emp_idcode=map.get("emp_idcode");
            String dept_idcode=map.get("dept_idcode");
            String emp_idnumber=map.get("emp_idnumber");
            String emp_projectleader=map.get("emp_projectleader");
            String emp_projectpayee=map.get("emp_projectpayee");
            String emp_judgeprojectleader=map.get("emp_judgeprojectleader");
            String emp_judgeprojectpayee=map.get("emp_judgeprojectpayee");
            String emp_incumbencystate=map.get("emp_incumbencystate");
            String emp_projectleaderid=map.get("emp_projectleaderid");
            String emp_projectpayeeid=map.get("emp_projectpayeeid");
            String part_type=map.get("part_type")!=null?map.get("part_type"):"";//主职
            String idtype_content=map.get("idtype_content")!=null?map.get("idtype_content"):"";//证件类型
            String competentorg_content=map.get("competentorg_content")!=null?map.get("competentorg_content"):"";//主管单位名称
            String incumbency_content=map.get("incumbency_content")!=null?map.get("incumbency_content"):"";//在职状态
            String emp_numbereffectiveness=map.get("emp_numbereffectiveness")!=null?map.get("emp_numbereffectiveness"):"";//员工编号有效性
            String empisvalid_content=map.get("empisvalid_content")!=null?map.get("empisvalid_content"):"";//员工编号有效性
            String emp_datavalid=map.get("emp_datavalid")!=null?map.get("emp_datavalid"):"";//人事资料有效期
            String emp_companyemail=map.get("emp_companyemail")!=null?map.get("emp_companyemail"):"";//公司邮箱
            String emp_personneltype=map.get("emp_personneltype")!=null?map.get("emp_personneltype"):"";//人员类别ID
            String persontype_content=map.get("persontype_content")!=null?map.get("persontype_content"):"";//人员类别
            sql=String.format(sql,emp_id,emp_idcode,emp_number,emp_name,dept_id,
                    dept_idcode,emp_idnumber,emp_mobilephone,emp_projectleader,emp_projectpayee
            ,emp_judgeprojectleader,emp_judgeprojectpayee,emp_incumbencystate,emp_entrydate,
                    emp_projectleaderid,emp_projectpayeeid,emp_sex,part_type,idtype_content,
                    competentorg_content,incumbency_content,emp_numbereffectiveness,empisvalid_content,
                    emp_datavalid,emp_companyemail,emp_personneltype,persontype_content,"1");
            SqlUtil.doNoQuery(sql);

            }
            getEngine().getOrganization().Reload();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }
}
